﻿using System;
using System.Drawing;
using System.Diagnostics;

using Microsoft.WindowsMobile.Status;

using iPhoneUI.Shell;

namespace iPhoneUI.Widgets
{
    public class ButtonWidget : TextWidget
    {
        private bool m_pushed;

        public event EventHandler Clicked;

        public ButtonWidget()
        {
            Font = ShellConfig.CreateFont(7, FontStyle.Regular);
        }

        public SystemProperty SystemProperty { get; set; }

        protected override void OnSetOwner()
        {
            if (SystemProperty != default(SystemProperty))
            {
                Badge badge = new Badge();
                badge.SystemProperty = SystemProperty;

                Decorations.Add(badge);
            }

            base.OnSetOwner();
        }

        public bool Pushed 
        {
            get
            {
                return m_pushed;
            }
            set
            {
                if (m_pushed != value)
                {
                    m_pushed = value;
                    OnPushedChanged();
                }
            }
        }

        public override void OwnerMouseDown(int x, int y)
        {
            if (HitTest(x, y))
                Pushed = true;
        }

        public override void OwnerMouseUp(int x, int y)
        {
            if (Pushed)
            {
                Pushed = false;
                if (HitTest(x, y))
                    OnClicked();
            }
        }

        protected virtual void OnPushedChanged()
        {
            Update();
        }

        protected override void OnDraw(Canvas canvas, Rectangle clipBounds)
        {
            if (string.IsNullOrEmpty(Text) == false)
            {
                SizeF size = canvas.MeasureString(Text, Font);
                RectangleF rect = new RectangleF(ClientArea.X, ClientArea.Y + ClientArea.Height - 1, Size.Width, size.Height * 2);
                
                using (StringFormat format = new StringFormat(StringFormatFlags.NoClip))
                using (Brush b = new SolidBrush(ForeColor))
                {
                    format.Alignment = StringAlignment.Center;
                    format.LineAlignment = StringAlignment.Near;
                    canvas.DrawString(Text, Font, b, rect, format);
                }
            }
        }

        protected virtual void OnClicked()
        {
            if (Clicked != null)
                Clicked(this, EventArgs.Empty);
        }
    }
}
